package com.ztom.v2;

/**
 * @author ZhangTao
 */
public class Code50BinaryTreeMaximumPathSum {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int maxPathSum(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int[] max = {Integer.MIN_VALUE};
        process(root, max);
        return max[0];
    }

    public int process(TreeNode node, int[] max) {
        if (node == null) {
            return 0;
        }
        int lm = Math.max(0, process(node.left, max));
        int rm = Math.max(0, process(node.right, max));
        // 更新最大路径和
        max[0] = Math.max(max[0], node.val + lm + rm);
        // 返回当前节点的最大贡献值
        return Math.max(lm, rm) + node.val;
    }
}
